/**
 * Copyright : www.orientpay.com , 2007-2011
 * Project : sqt_spider_main
 * $Id$
 * $Revision$
 * Last Changed by ZhouXushun at 2011-5-10 下午03:00:37
 * $URL$
 * 
 * Change Log
 * Author      Change Date    Comments
 *-------------------------------------------------------------
 * ZhouXushun     2011-5-10        Initailized
 */

package com.youthor.spider.core.monitor;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.youthor.spider.core.Constants;
import com.youthor.spider.core.dto.HttpProxyDTO;

/**
 * 代理信息监控器
 *
 */
public class HttpProxyFileMonitor implements Runnable{
	protected Log log = LogFactory.getLog(getClass());
	
	private int second;
    private String fileFullPath;
    Thread runner;
    private String lastModTime;
    private boolean isInit;
    
    /**
     * @param second   时间间隔
     * @param filePath 文件路径
     */
    public HttpProxyFileMonitor(int second, String fileFullPath) {
    	if(second < 0){
    		second = 10;
    	}
    	
        this.second = second*1000;
        this.fileFullPath = fileFullPath;
        
        File dirFile = new File(fileFullPath);
        if(!dirFile.isFile()){
        	log.error("ERROR: can not find the http proxy file!");
        	throw new IllegalArgumentException("can not find http proxy file :" + fileFullPath);
        }
        
    }
    
    public void onStart(){
        runner = new Thread(this);
        runner.start();
    }
    
    public void run() {
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
        while(true) {
	        try {
	            watch();
	            Thread.sleep(second);
	        } 
	        catch (InterruptedException e) {
	            e.printStackTrace();
	        }
        }
    }
    
    /*
     * 监控
     */
    protected void watch(){
    	File dirFile = new File(fileFullPath);
    	String fileModTime = String.valueOf(dirFile.lastModified());
        if(!fileModTime.equals(lastModTime)){
        	lastModTime = fileModTime;
        	log.debug("file changed ->" + lastModTime);
        	resetHolder();
        }
        if(!isInit()){
        	isInit = true;
        }
    }
    
    protected void resetHolder(){
    	HttpProxyHolder holder = HttpProxyHolder.getInstance();
    	if(holder.isLocked()){
    		return;
    	}
    	
    	try{
    		holder.removeAll();
	    	holder.setLocked(true);
	    	File file = new File(fileFullPath);
	        //创建读取流
	        BufferedReader br = new BufferedReader(new FileReader(file)); 
	        String line = "";
	        while((line = br.readLine()) != null){
	            if(line != null && line.trim().length() > 0){
	                String [] param = line.split(Constants.COMMA_SIGN_SPLIT_NAME,-1);
	                if(param.length != 5){
	                	log.info("can not parse http proxy info: " + line);
	                	continue;
	                }
	                if(StringUtils.isBlank(param[0])){
	                	log.info("the ip addr is null: " + param[0]);
	                	continue;
	                }
	                HttpProxyDTO dto = new HttpProxyDTO();
	                
	                dto.setIpAddress(param[0]);
	                if(StringUtils.isNotBlank(param[1])){
	                	dto.setPort(NumberUtils.toInt(param[1]));
	                }
	                if(StringUtils.isNotBlank(param[2])){
	                	dto.setNeedAuth(true);
	                	dto.setAuthName(param[2]);
	                	dto.setAuthPwd(param[3]);
	                }
	                if(StringUtils.isNotBlank(param[4])){
	                	dto.setProportion(NumberUtils.toInt(param[4]));
	                }
	                holder.addHttpProxyDTO(dto);
	            }
	        }
    	}
    	catch(Exception e){
    		log.error("ERROR", e);
    	}
    	finally{
    		holder.setLocked(false);
    	}
    }

    
	public boolean isInit() {
		return isInit;
	}

	public void setInit(boolean isInit) {
		this.isInit = isInit;
	}
}
